package com.heima.heima_netty.nio.c3;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.List;

import static com.heima.heima_netty.nio.c1.ByteBufferUtil.debugRead;

/**
 * @author felix
 * @date 2024/9/10 14:54
 *
 */
@Slf4j
public class ServerSelector01 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // selector要配合非阻塞模式使用
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8089));

        // 1.创建一个selector
        Selector selector = Selector.open();
        // 2.将channel注册到selector上
        SelectionKey sscKey = ssc.register(selector, 0, null);
        log.debug("register Key:{}",sscKey);
        // 3.指定selector要监听的事件类型
        sscKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true){
            // 4.启动selector监听
            // 没有事件时阻塞，有事件时不会阻塞，进行处理或取消
            selector.select();
            // 5.获取监听到的事件集合
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                //6.获取事件并处理
                SelectionKey key = iterator.next();
                log.debug("get Key:{}",key);
                // 取消处理
//                key.cancel();
                ServerSocketChannel sc = (ServerSocketChannel)key.channel();
                log.debug("get sc:{}",sc);
                sc.accept();
            }
            }
    }
}
